package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.enums.WorkerCertificationEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.*;
import com.jzo2o.mvc.handler.UserInfoHandlerImpl;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: LiuLi
 * @Date: 2025/09/18 上午11:39
 * @Description: 服务人员认证审核服务实现类
 */
@Service
@Slf4j
public class WorkerCertificationAuditServiceImpl extends ServiceImpl<WorkerCertificationAuditMapper, WorkerCertificationAudit> implements IWorkerCertificationAuditService {

    @Resource

    private IWorkerCertificationService workerCertificationService;
    @Resource
    private IWorkerCertificationAuditService workerCertificationAuditService;
    @Resource
    private UserInfoHandlerImpl userInfoHandlerImpl;
    @Resource
    private IServeProviderService serveProviderService;



    /**
     * 认证审核通过
     *
     * @param id                认证审核ID
     * @param certificationStatus 认证状态
     * @param rejectReason      拒绝原因
     */
    @Override
    public void updateWorkerCertification(Long id, Integer certificationStatus, String rejectReason) {
        log.info("传来的认证状态为Integer[{}]", certificationStatus);
        //1.校验认证审核是否存在
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditService.getById(id);
        if (workerCertificationAudit == null) {
            throw new BadRequestException("认证审核不存在");
        }
        //2.校验认证审核状态
        if (!workerCertificationAudit.getAuditStatus().equals(WorkerCertificationEnum.CERTIFICATION_STATUS_WAIT.getCode())) {
            log.info("认证审核状态异常，当前状态：{}", workerCertificationAudit.getAuditStatus());
            throw new BadRequestException("认证审核状态异常");
        }
        //如果认证状态为通过
        if (certificationStatus.equals(WorkerCertificationEnum.CERTIFICATION_STATUS_SUCCESS.getCode())) {
            //3.更新worker_certification_audit里面的认证状态
            LambdaUpdateWrapper<WorkerCertificationAudit> updateWrapper = Wrappers.lambdaUpdate(WorkerCertificationAudit.class)
                    //设置审核状态
                    .set(WorkerCertificationAudit::getAuditStatus, WorkerCertificationEnum.CERTIFICATION_STATUS_APPLYING.getCode())
                    //设置认证人id
                    .set(WorkerCertificationAudit::getAuditorId, userInfoHandlerImpl.currentUserInfo().getId())
                    //设置认证人姓名
                    .set(WorkerCertificationAudit::getAuditorName, userInfoHandlerImpl.currentUserInfo().getName())
                    //设置认证时间
                    .set(WorkerCertificationAudit::getAuditTime, LocalDateTime.now())
                    //设置更新时间
                    .set(WorkerCertificationAudit::getUpdateTime, LocalDateTime.now())
                    //设置认证状态
                    .set(WorkerCertificationAudit::getCertificationStatus, certificationStatus)
                    //设置拒绝原因
                    .set(WorkerCertificationAudit::getRejectReason, rejectReason)
                    .eq(WorkerCertificationAudit::getId, id);
            workerCertificationAuditService.update(null, updateWrapper);
            //4.更新worker_certification里面的认证状态
            LambdaUpdateWrapper<WorkerCertification> updateWrapper2 = Wrappers.lambdaUpdate(WorkerCertification.class)
                    //设置认证状态
                    .set(WorkerCertification::getCertificationStatus, WorkerCertificationEnum.CERTIFICATION_STATUS_SUCCESS.getCode())
                    //设置更新时间
                    .set(WorkerCertification::getUpdateTime, LocalDateTime.now())
                    //设置认证时间
                    .set(WorkerCertification::getCertificationTime, LocalDateTime.now())
                    .eq(WorkerCertification::getIdCardNo, workerCertificationAudit.getIdCardNo());
            workerCertificationService.update(null, updateWrapper2);
            //5.更新服务人员表里面的认证状态
            LambdaUpdateWrapper<ServeProvider> updateWrapper3 = Wrappers.lambdaUpdate(ServeProvider.class)
                    .set(ServeProvider::getName, workerCertificationAudit.getName())
                    .set(ServeProvider::getSettingsStatus, 1)
                    .set(ServeProvider::getUpdateTime, LocalDateTime.now())
                    .eq(ServeProvider::getId, workerCertificationAudit.getServeProviderId());
            serveProviderService.update(null, updateWrapper3);
        } else if (certificationStatus.equals(WorkerCertificationEnum.CERTIFICATION_STATUS_FAILED.getCode())) {
            //3.更新worker_certification_audit里面的认证状态
            LambdaUpdateWrapper<WorkerCertificationAudit> updateWrapper = Wrappers.lambdaUpdate(WorkerCertificationAudit.class)
                    //设置审核状态
                    .set(WorkerCertificationAudit::getAuditStatus, WorkerCertificationEnum.CERTIFICATION_STATUS_APPLYING.getCode())
                    //设置认证人id
                    .set(WorkerCertificationAudit::getAuditorId, userInfoHandlerImpl.currentUserInfo().getId())
                    //设置认证人姓名
                    .set(WorkerCertificationAudit::getAuditorName, userInfoHandlerImpl.currentUserInfo().getName())
                    //设置认证时间
                    .set(WorkerCertificationAudit::getAuditTime, LocalDateTime.now())
                    //设置更新时间
                    .set(WorkerCertificationAudit::getUpdateTime, LocalDateTime.now())
                    //设置认证状态
                    .set(WorkerCertificationAudit::getCertificationStatus, WorkerCertificationEnum.CERTIFICATION_STATUS_FAILED.getCode())
                    //设置拒绝原因
                    .set(WorkerCertificationAudit::getRejectReason, rejectReason)
                    .eq(WorkerCertificationAudit::getId, id);
            workerCertificationAuditService.update(null, updateWrapper);
            //4.更新worker_certification里面的认证状态
            LambdaUpdateWrapper<WorkerCertification> updateWrapper2 = Wrappers.lambdaUpdate(WorkerCertification.class)
                    //设置认证状态
                    .set(WorkerCertification::getCertificationStatus, WorkerCertificationEnum.CERTIFICATION_STATUS_FAILED.getCode())
                    //设置更新时间
                    .set(WorkerCertification::getUpdateTime, LocalDateTime.now())
                    .eq(WorkerCertification::getIdCardNo, workerCertificationAudit.getIdCardNo());
            workerCertificationService.update(null, updateWrapper2);
            //5.更新服务人员表里面的认证状态
            LambdaUpdateWrapper<ServeProvider> updateWrapper3 = Wrappers.lambdaUpdate(ServeProvider.class)
                    .set(ServeProvider::getName, workerCertificationAudit.getName())
                    .set(ServeProvider::getSettingsStatus, 0)
                    .set(ServeProvider::getUpdateTime, LocalDateTime.now())
                    .eq(ServeProvider::getId, workerCertificationAudit.getServeProviderId());
            serveProviderService.update(null, updateWrapper3);
        }
    }

    /**
     * 添加服务人员认证信息
     *
     * @param workerCertificationAuditAddReqDTO 服务人员认证信息
     */
    @Override
    public void add(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        // 将请求DTO转换为实体类
        WorkerCertificationAudit workerCertificationAudit = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertificationAudit.class);

        // 设置默认值
        workerCertificationAudit.setAuditStatus(0); // 0：未审核
        workerCertificationAudit.setCertificationStatus(WorkerCertificationEnum.CERTIFICATION_STATUS_APPLYING.getCode()); // 1：认证中
        workerCertificationAudit.setCreateTime(LocalDateTime.now());
        workerCertificationAudit.setUpdateTime(LocalDateTime.now());

        // 保存到worker_certification_audit表
        this.save(workerCertificationAudit);

        log.info("服务人员认证申请保存成功，服务人员ID：{}", workerCertificationAudit.getServeProviderId());
    }

    /**
     * 分页查询认证申请信息
     *
     * @param queryDTO 查询参数
     * @return 分页结果
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> pageQuery(WorkerCertificationAuditPageQueryReqDTO queryDTO) {
        // 解析分页参数
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(queryDTO, WorkerCertificationAudit.class);

        // 构建查询条件
        LambdaQueryWrapper<WorkerCertificationAudit> queryWrapper = new LambdaQueryWrapper<>();

        // 按姓名模糊查询
        if (queryDTO.getName() != null) {
            queryWrapper.like(WorkerCertificationAudit::getName, queryDTO.getName());
        }

        // 按身份证号模糊查询
        if (queryDTO.getIdCardNo() != null) {
            queryWrapper.like(WorkerCertificationAudit::getIdCardNo, queryDTO.getIdCardNo());
        }

        // 按审核状态查询
        if (queryDTO.getAuditStatus() != null) {
            queryWrapper.eq(WorkerCertificationAudit::getAuditStatus, queryDTO.getAuditStatus());
        }

        // 按认证状态查询
        if (queryDTO.getCertificationStatus() != null) {
            queryWrapper.eq(WorkerCertificationAudit::getCertificationStatus, queryDTO.getCertificationStatus());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(WorkerCertificationAudit::getCreateTime);

        // 执行分页查询
        Page<WorkerCertificationAudit> resultPage = this.page(page, queryWrapper);

        // 转换为响应DTO
        List<WorkerCertificationAuditResDTO> resDTOList = resultPage.getRecords().stream()
                .map(record -> BeanUtil.toBean(record, WorkerCertificationAuditResDTO.class))
                .collect(Collectors.toList());

        // 返回分页结果
        return PageUtils.toPage(resultPage, WorkerCertificationAuditResDTO.class);
    }

}
